from app import mysql

def generate_account():
    import random
    length = random.randint(6, 9)  # 6-9位
    return ''.join(str(random.randint(0, 9)) for _ in range(length))

def check_username_exists(username):
    cursor = mysql.connection.cursor()
    cursor.execute("SELECT * FROM users WHERE username = %s", (username,))
    result = cursor.fetchone()
    cursor.close()
    return result is not None

def check_account_exists(account):
    cursor = mysql.connection.cursor()
    cursor.execute("SELECT * FROM users WHERE account = %s", (account,))
    result = cursor.fetchone()
    cursor.close()
    return result is not None

def create_user(username, password):
    account = generate_account()
    while check_account_exists(account):
        account = generate_account()
    
    cursor = mysql.connection.cursor()
    cursor.execute(
        "INSERT INTO users (username, password, account) VALUES (%s, %s, %s)",
        (username, password, account)
    )
    mysql.connection.commit()
    cursor.close()
    return account